// pages/sureget/sureget.js
var utils = require("../../utils/md5.js")
var acid = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderData: null,
    addressList: [],
    orderId: null,

    selectorArr: ['1Kg以内', '1Kg～2Kg', '2Kg~3Kg', '3Kg~4Kg', '4Kg~5Kg'],
    selectorValue: 0
  },

  payBtnClick: function() {
    if (addressList.length < 1) {
      wx.showToast({
        title: '请填写地址信息',
        icon: 'none',
      })
      return
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    acid = options.acid;
  },

  // 倒计时方法
  countDown: function(leftTime) {
    var that = this;

    var leftHours = Math.floor(leftTime / 60 / 60);
    if (leftHours <= 9) {
      leftHours = '0' + leftHours;
    }
    var leftMinutes = Math.floor(leftTime / 60 % 60);
    if (leftMinutes <= 9) {
      leftMinutes = '0' + leftMinutes;
    }
    var leftSeconds = Math.floor(leftTime % 60);
    if (leftSeconds <= 9) {
      leftSeconds = '0' + leftSeconds;
    }
    that.setData({
      countDownTime: leftHours + ":" + leftMinutes + ":" + leftSeconds,
    })

    if (leftTime > 0) {
      setTimeout(function() {
        leftTime--;
        that.countDown(leftTime);
      }, 1000);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  addressClick: function() {
    var that = this;
    wx.navigateTo({
      url: '../address/address?orderId=' + that.data.orderId,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    var that = this;
    /// 创建订单
    wx.showLoading()
    wx.request({
      url: getApp().globalData.order_add_url,
      data: {
        userId: getApp().globalData.userInfo.userId,
        acid: acid,
      },
      success(res) {
        console.log(res)
        if (res.data.code != 0) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          return
        }

        that.amount = res.data.data.amount;
        that.setData({
          orderData: res.data.data,
          orderId: res.data.data.orderId,
          addressList: res.data.data.addressList,
        })
        var leftTime = res.data.data.dateline + 24 * 60 * 60 - res.data.data.current;
        console.log(leftTime)
        that.countDown(leftTime);
      },
      complete() {
        wx.hideLoading()
      }
    })
  },



  // 支付
  payBtnClick: function() {

    var that = this;
    if (this.data.addressList.length < 1) {
      wx.showToast({
        title: '请填写你的地址信息',
        icon: 'none'
      })
      return;
    }

    if (this.data.orderData == null || this.data.orderData == undefined) {
      wx.showToast({
        title: '数据异常',
        icon: 'none',
      })
      return;
    }

    console.log(getApp().globalData.openid, getApp().globalData.userInfo.userId, getApp().globalData.acid, this.amount, that.data.addressList[0].id)
    wx.showLoading()
    wx.request({
      url: getApp().globalData.wx_prepay_url,
      data: {
        openId: getApp().globalData.openid,
        userId: getApp().globalData.userInfo.userId,
        acid: acid,
        amount: that.amount,
        addressid: that.data.addressList[0].id,
        orderId: that.data.orderId,
      },
      success: function(res) {
        console.log(res)

        if (res.data.code == -1) {
          wx.showModal({
            title: '支付成功',
            content: '支付已完成',
            showCancel: true,
            confirmText: "确定",
            showCancel: false,
            success: function (res) {
              wx.navigateBack({
                delta: 1,
              })
            },
            fail: function (res) { },
            complete: function (res) { },
          })
          return;
        }

        if (res.data.code != 0) {
          wx.showModal({
            title: '支付失败',
            content: '支付失败请联系管理员',
            showCancel: true,
            confirmText: "确定",
            showCancel: false,
            success: function (res) {
              wx.navigateBack({
                delta: 1,
              })
            },
            fail: function (res) { },
            complete: function (res) { },
          })
          return;
        }

        /// 真正调起支付
        let nonceStr = res.data.data.nonce_str;
        let prepayId = res.data.data.prepayId;
        let timeStamp = res.data.data.timeStamp;
        let paySign = utils.hexMD5('appId=wx67183df13d14b063&nonceStr=' + nonceStr + '&package=' + prepayId + '&signType=MD5&timeStamp=' + timeStamp + '&key=1C48986B062E62201F19843330F0C45E').toUpperCase();
        // let paySign = res.data.data.orderMsg.sign;
        console.log(paySign);

        wx.requestPayment({
          timeStamp: timeStamp,
          nonceStr: nonceStr,
          package: prepayId,
          signType: 'MD5',
          paySign: paySign,
          success: function(res) {
            wx.showModal({
              title: '支付成功',
              content: '支付已完成',
              showCancel: true,
              confirmText: "确定",
              showCancel: false,
              success: function(res) {
                wx.navigateBack({
                  delta: 1,
                })
              },
              fail: function(res) {},
              complete: function(res) {},
            })
          },
          fail: function(res) {

          },
        })

      },
      fail(err) {

      },
      complete() {
        wx.hideLoading()
      }
    })

  },


  // 查询运费
  queryAmountBtnClick: function() {
    this.setData({
      showYunfei: true
    })
  },

  maskViewClick: function() {
    this.setData({
      showYunfei: false
    })
  },

  bindRegionChange: function(e) {
    console.log(e)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.target.id == 0) {
      this.setData({
        region: e.detail.value
      })
    } else {
      this.setData({
        toRegion: e.detail.value
      })
    }
  },

  weightInputChange: function(e) {
    console.log(e)
    this.setData({
      weight: e.detail.value
    })
  },


  weightChange: function(e) {
    this.setData({
      selectorValue: e.detail.value
    })
  },

  queryBtnClick: function() {
    var that = this;

    if (this.data.region == undefined || this.data.region == null || this.data.toRegion == undefined || this.data.toRegion == null) {
      wx.showToast({
        title: '请输入地址进行查询',
        icon: 'none'
      })
      return
    }



    var totalWeight = parseInt(that.data.selectorValue) + 0.5;

    wx.request({
      url: getApp().globalData.calculate_address_amount_url,
      data: {
        fromProvince: that.data.region[0],
        fromCity: that.data.region[1],
        toProvince: that.data.toRegion[0],
        toCity: that.data.toRegion[1],
        totalWeight: totalWeight,
      },
      success(res) {
        console.log(res)
        that.setData({
          addressAmount: res.data.data.amount,
          sz: res.data.data.sz,
          xz: res.data.data.xz,
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    if (e.from == 'menu') { // 分享小程序

      return {
        title: '快来加入闲置会发光，做最环保的时髦精>>',
        path: '/pages/login/login',
        imageUrl: '/resources/share_miniprogram.png',
      }
    }
  }
})
